<template>
  <div class="reading-pane">
    <div v-if="!chapter && !allChapters" class="empty-hint">
      <el-empty description="请选择章节" />
    </div>

    <div v-else-if="chapter" class="chapter-full">
      <h2 class="chapter-title">{{ chapter.title }}</h2>
      <template v-for="(sec, sIndex) in (chapter.sections || [])" :key="sIndex">
        <h3 class="section-title" :id="sectionAnchor(chapter.id, sIndex)">{{ sec.title }}</h3>
        <ParagraphBlock
          v-for="(p, pIndex) in (sec.paragraphs || [])"
          :key="pIndex"
          :original="p.original"
          :translation="p.translation"
          :anchor-id="paragraphAnchor(chapter.id, sIndex, pIndex)"
          :highlight="shouldHighlight(chapter.id, sIndex, pIndex)"
          :book-id="chapter.bookId || activeBookIdInternal"
          :book-title="activeBookTitle"
          :chapter-id="chapter.id"
          :section-index="sIndex"
          :paragraph-index="pIndex"
        />
      </template>
    </div>

    <div v-else class="all-chapters">
      <template v-for="ch in allChapters" :key="ch.id">
        <h2 class="chapter-title" :id="chapterAnchor(ch.id)">第 {{ ch.id }} 章 · {{ ch.title }}</h2>
        <template v-for="(sec, sIndex) in (ch.sections || [])" :key="sIndex">
          <h3 class="section-title" :id="sectionAnchor(ch.id, sIndex)">{{ sec.title }}</h3>
          <ParagraphBlock
            v-for="(p, pIndex) in (sec.paragraphs || [])"
            :key="pIndex"
            :original="p.original"
            :translation="p.translation"
            :anchor-id="paragraphAnchor(ch.id, sIndex, pIndex)"
            :highlight="shouldHighlight(ch.id, sIndex, pIndex)"
            :book-id="ch.bookId || activeBookIdInternal"
            :book-title="activeBookTitle"
            :chapter-id="ch.id"
            :section-index="sIndex"
            :paragraph-index="pIndex"
          />
        </template>
      </template>
    </div>
  </div>
</template>

<script setup>
const props = defineProps({
  chapter: { type: Object, default: null },
  allChapters: { type: Array, default: null },
  scrollTo: { type: Object, default: null } // { chapterId, sectionIndex, paragraphIndex? }
})

function chapterAnchor(chapterId) {
  return `chapter-${chapterId}`
}
function sectionAnchor(chapterId, sectionIndex) {
  return `chapter-${chapterId}-section-${sectionIndex}`
}
function paragraphAnchor(chapterId, sectionIndex, paragraphIndex) {
  return `chapter-${chapterId}-section-${sectionIndex}-p-${paragraphIndex}`
}

function shouldHighlight(chId, sIdx, pIdx) {
  if (!props.scrollTo) return false
  return props.scrollTo.chapterId === chId && props.scrollTo.sectionIndex === sIdx && props.scrollTo.paragraphIndex === pIdx
}

import { watch, nextTick, onMounted, computed as vueComputed } from 'vue'
import { useBooksStore } from '@/store/books'
import ParagraphBlock from './ParagraphBlock.vue'

// 允许外部固定头部造成遮挡时偏移（像顶部工具栏高度）
const SCROLL_OFFSET = 70 // 可按需调整 / 或改造成 prop

// 提供 activeBookId 和 标题 给子组件
const booksStore = useBooksStore()
const activeBookIdInternal = vueComputed(() => booksStore.activeBookId)
const activeBookTitle = vueComputed(() => booksStore.activeBook?.title || '')

function smoothScrollToEl(el) {
  if (!el) return
  // 使用 window 滚动，避免某些情况下 scrollIntoView 被父级 overflow 影响
  const rect = el.getBoundingClientRect()
  const targetTop = rect.top + window.scrollY - SCROLL_OFFSET
  window.scrollTo({ top: targetTop < 0 ? 0 : targetTop, behavior: 'smooth' })
}

async function tryScroll(val, attempt = 0) {
  if (!val) return
  // 生成 id
  let id
  if (typeof val.paragraphIndex === 'number') {
    id = paragraphAnchor(val.chapterId, val.sectionIndex, val.paragraphIndex)
  } else {
    id = sectionAnchor(val.chapterId, val.sectionIndex)
  }
  await nextTick()
  const el = document.getElementById(id)
  if (el) {
    // 调试日志
    if (attempt > 0) {
      console.debug('[ReadingPane] scroll success after retries', { id, attempt })
    } else {
      console.debug('[ReadingPane] scroll success', { id })
    }
    smoothScrollToEl(el)
    return
  }
  // 若未找到，最多重试 12 次（~12 * 60ms ≈ 720ms）
  if (attempt < 12) {
    if (attempt === 0) console.debug('[ReadingPane] first attempt not found, retrying', { id })
    setTimeout(() => tryScroll(val, attempt + 1), 60)
  }
    console.warn('[ReadingPane] failed to locate target id after retries', { id, val })
}
// 监听 scrollTo 变化
watch(() => props.scrollTo, (val) => { if (val) tryScroll(val) }, { deep: true })

// 当章节对象变化时，如果已有 scrollTo 目标再尝试一次（解决初次加载 race）
watch(() => props.chapter, () => { if (props.scrollTo) tryScroll(props.scrollTo) })
onMounted(() => { if (props.scrollTo) tryScroll(props.scrollTo) })
</script>

<style scoped>
.reading-pane { flex:1; background:#fffffffa; backdrop-filter: blur(4px); border:1px solid #e2e8f0; border-radius:20px; padding:30px 40px 80px; min-height:600px; box-shadow:0 8px 26px -10px rgba(0,0,0,.16); overflow:hidden; }
.chapter-title { margin:40px 0 18px; font-size:26px; font-weight:600; color:#2c3e50; letter-spacing:1px; position:relative; }
.chapter-title:first-of-type { margin-top:0; }
.section-title { margin:28px 0 14px; font-size:18px; font-weight:500; color:#34495e; }
/* paragraph 样式移至 ParagraphBlock 组件内部 */
.empty-hint { padding:60px 0; }
@media (max-width: 960px) { .reading-pane { padding:24px 24px 60px; } }
</style>
